﻿using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TRKUTIL.Text
{
    internal class ProcessRunner
    {
        public string Output { get; private set; }
        public string Error { get; private set; }
        public int ExitCode { get; private set; }

        public static ProcessRunner Run(string fileName, string arguments)
        {

            using (var process = Process.Start(new ProcessStartInfo
            {
                FileName = fileName,
                Arguments = arguments,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            }))
            {
                var result = new ProcessRunner
                {
                    Output = process.StandardOutput.ReadToEnd(),
                    Error = process.StandardError.ReadToEnd()
                };
                process.WaitForExit(500);
                if (!process.HasExited)
                {
                    process.Kill();
                    Assert.Fail("Process runs too long, possible deadlock");
                }
                result.ExitCode = process.ExitCode;

                return result;
            }
        }
    }
}
